<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			#small-box{
				width: 400px;
				height: 400px;
				background-image: url(./img/13.jpg);
				background-size: 400px 400px;
				background-repeat: no-repeat;
				position: absolute;
				top: 200px;
				left: 200px;
				
			}
			#mask{
				width: 100px;
				height: 100px;
				background-color: crimson;
				opacity: 0.4;
				position: absolute;
				cursor: move;
				display: none;
				
			}
			#big-box{
				width: 400px;
				height: 400px;
				background-image: url(img/13.jpg);
				background-size: 1600px 1600px;
				position: absolute;
				top: 200px;
				left: 800px;
				display: none;
			}
		</style>
	</head>
	<body>
		<div id="small-box">
			<div id="mask">
				
			</div>
		</div>
		<div id="big-box">
			
		</div>
	</body>
</html>
<script type="text/javascript">
	class Magnifier{
		constructor(smallBox,Mask,bigBox) {
		   this.oSmallBox = smallBox;
		   this.oMask = Mask;
		   this.oBigBox = bigBox;
		   this.eventBind();
		}
		//鼠标移入图片让放大镜和大图显示
		mouseover(){
			let that = this;
			this.oSmallBox.onmouseover = function(){
				that.oMask.style.display = "block";
				that.oBigBox.style.display = "block";
			}
		}
		//鼠标移出图片让放大镜和大图隐藏
		mouseout(){
			let that = this;
			this.oSmallBox.onmouseout = function(){
				that.oMask.style.display = "none";
				that.oBigBox.style.display = "none";
			}
		}
		
		//鼠标移动让放大镜跟随鼠标
		mousemove(){
			let that = this;
			// 鼠标在oSmallBox上移动时候执行以下函数
			this.oSmallBox.onmousemove = function(evt){
				let e = evt || event;
				//左边和上边的的距离
				let left = e.pageX - this.offsetLeft - that.oMask.offsetWidth/2 ;
				let top =  e.pageY  - this.offsetTop  - that.oMask.offsetHeight/2 ;
				
				//这是边框条件，控制放大镜的边界
				if(left < 0 ){
					left = 0;
				}
				
				let maxLeft = this.offsetWidth -that.oMask.offsetWidth;
				if(left>maxLeft){
					left = maxLeft;
				}
				//上下边框界限
				if(top < 0 ){
					top = 0;
				}
				let maxTop = this.offsetHeight - that.oMask.offsetHeight;
				if(top>maxTop){
					top = maxTop;
				}
				
				// 改变放大镜的位置让跟随鼠标移动;
				that.oMask.style.left = left + "px";
				that.oMask.style.top = top + "px";
				
				//设置放大镜移动的时候大图按照比例向相反方向移动背景图的位置
				let x = that.oBigBox.offsetWidth*left/that.oMask.offsetWidth;
				let y = that.oBigBox.offsetHeight*top/that.oMask.offsetHeight;
				
				that.oBigBox.style.backgroundPositionX = -x + "px";
				that.oBigBox.style.backgroundPositionY = -y + "px";
							
			}
		}
		
		eventBind(){
			this.mouseover();
			this.mouseout();
			this.mousemove();
		}
		
	}
	
	//获取绑定元素
	let oSmallBox = document.getElementById("small-box");
	let oMask = document.getElementById("mask");
	let oBigBox = document.getElementById("big-box");
	let d = new Magnifier(oSmallBox,oMask,oBigBox);
</script>